<?php

namespace houniao;

use catchAdmin\api\model\Order;
use catchAdmin\customs\model\HnOrderDetail;
use catchAdmin\externalGoods\model\Category;
use catchAdmin\externalGoods\model\GoodsAttribute;
use catchAdmin\externalGoods\model\GoodsRule;
use catchAdmin\externalGoods\model\MessageQueue;
use catchAdmin\externalGoods\model\TenantGoods;
use catchAdmin\externalGoods\service\GoodsService;
use catchAdmin\externalGoods\model\Notify as externalNotify;
//use catcher\base\CatchRequest as Request;
use catchAdmin\externalGoods\service\OrderLogisticsTrackService;
use catchAdmin\externalGoods\service\OrderService;
use houniao\api\v1\Goods;
use houniao\api\v1\Order as OrderApi;
use think\facade\Db;
use think\Request;
use catcher\CatchResponse;
use houniao\tools\Params;
use think\Exception;
use think\facade\Log;
use think\response\Json;

class SyncShop1110
{
    protected $app_key = '62ae4e5e226a972c';
    protected $secret='2b7db6bdb6cc689de3cda48a4fe80095';
    protected $shop_tenant_id = 1110;
    protected $_tenant_id = 10144;
    protected $server = "mysql_df_remote";
    protected $percet = 1.10;


    const GOODS_ADD = 'goods.add';//商品新增
    const GOODS_UPD = 'goods.update';//商品更新
    const GOODS_SHELVE = 'goods.shelve';//商品上架
    const GOODS_UNSHELVE = 'goods.unshelve';//商品下架
    const GOODS_PRICE = 'goods.price';//商品价格库存
    const GOODS_STOCK = 'goods.stock';//商品库存
    const ORDER_SEND = 'order.send';//订单发货
    const ORDER_STATUS = 'order.status';//订单状态更新
//    const AFTER_SALE_STATUS = 'after.sale.status';//售后处理更新
    const ORDER_TRACK = 'track.info';//物流通知

    public function notify(Request $request){



        $data = $request->post();


        //商品新增
//        $data = '{"type":"goods.add","data":{"goods_spu":"HK10959893","goods_name":"Swisse/瑞思 血橙亮白粘土泥面膜 70g","old_goods_spu":""},"sign":"fb06c3d0c0cefc1735a110ac927e9d82"}';
//        $data = json_decode($data,true);

//        $data = '{"type":"goods.shelve","data":{"goods_spu":"BS00000081","goods_name":"【每日推荐】荷兰牛栏Nutrilon奶粉4段800g【新旧版本随机发货】","old_goods_spu":""},"sign":"886664f552ac970775f96278df6a8bf0"}';
//        $data = json_decode($data,true);


////物流
//        $data = '{
//  "type": "track.info",
//  "data": {
//    "order_no": "1",
//    "express_no": "1"
//  },
//  "sign": "a6127e2a86e6d68c03f0556ad3c96976"
//}';
//                $data = json_decode($data,true);

//        //订单发货
//        $data = '{"type":"order.send","data":{"source_order_no":"2","order_no":"3","express":[{"express_no":"1","express_name":"1","express_code":"1","delivery_time":"1687324840","goods_num":"1","goods_spu":"1","sku_id":"1","sku_name":"1"}],"order_goods":[{"express_no":"1","express_name":"1","express_code":"1","delivery_time":"1687324840","goods_num":"1","goods_spu":"1","sku_id":"1","sku_name":"1"}]},"sign":"3070f7ee378168c4586975a5b4f800f9"}';
//        $data = json_decode($data,true);


//        //商品新增
//        $data = '{"type":"goods.add","data":{"goods_spu":"BS00033612","goods_name":"Swisse/瑞思 血橙亮白粘土泥面膜 70g","old_goods_spu":""},"sign":"fb06c3d0c0cefc1735a110ac927e9d82"}';
//        $data = json_decode($data,true);

//        //物流通知
//        $data = '{"type":"track.info","data":{"order_no":"2023122845406","express_no":"YT2512270068123"},"sign":"17f307a22011134829c82654fa61ef77"}';
//        $data = json_decode($data,true);

        //判断小池子是否选择了商品
        $find = (new TenantGoods())->where([
            'goods_spu'=>$data['data']['goods_spu'],
            'tenant_id'=>$this->_tenant_id
        ])->find();
        if(!$find) {
            echo "warning";
            die();
        }

        $result = false;
        Db::startTrans();
        try {
            switch ($data['type']){
                case self::GOODS_ADD:
                    $msg = '商品新增';
                    $result=  $this->notifyGoodsAdd($data['data']['goods_spu']);
                    break;
                case self::GOODS_UPD:
                    $msg = '商品更新';
                    $result=  $this->notifyGoodsUpdate($data['data']['goods_spu']);
                    break;
                case self::GOODS_SHELVE:
                    $msg = '商品上架';
                    $result = $this->notifyGoodsUpdate($data['data']['goods_spu']);
                    break;
                case self::GOODS_UNSHELVE:
                    $msg = '商品下架';
//                    $result = $goodsService->notifyGoodsUnShelveBySPU($data['data']['goods_spu']);
                    $result = $this->notifyGoodsUpdate($data['data']['goods_spu']);
                    break;
                case self::GOODS_PRICE:
                    $msg = '商品价格库存更新';
                    $result = $this->notifyGoodsUpdate($data['data']['goods_spu']);
                    break;
                case self::GOODS_STOCK:
                    $msg = '商品库存更新';
                    $result = $this->notifyGoodsUpdate($data['data']['goods_spu']);
                    break;
                case self::ORDER_TRACK:
                    $msg = '物流通知';
//                    $result = $this->notifyTrack($data['data']);
                    $result = $this->notifyTrack($data['data']);
                    break;
                case self::ORDER_SEND:
                    $msg = '订单发货通知';
                    $result = $this->notifySend($data['data']);
                    break;
                case self::ORDER_STATUS:
                    $msg = '订单状态更新通知';
                    $result = $this->notifyOrderStatusSend($data['data']);
                    break;
                default:
                    $msg = '未知';
                    $result = false;
            }


            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            $remark = $exception->getMessage();
        }

        if($result){
            echo "SUCCESS";
        }else{
            echo 'failed';
        }
        die();
    }

    public function test(Request $request){
        //dd($request->post());
        die('success');
    }

    //通知新增商品
    public function notifyGoodsAdd($goods_spu){

        //查询商品是否存在
        $is_exist =  Db::connect($this->server)->table('db_product')
            ->where([
                'ifshow'=>1,
                'prod'=>$goods_spu,
                'tenant_id'=>$this->shop_tenant_id
            ])
            ->find();

        if($is_exist){
            return $this->updateGoodsInfo($goods_spu);
        }

        return  $this->addGoods($goods_spu);
    }

    //通知修改商品信息
    public function notifyGoodsUpdate($goods_spu){
        //查询商品是否存在
        $is_exist =  Db::connect($this->server)->table('db_product')
            ->where([
                'ifshow'=>1,
                'prod'=>$goods_spu,
                'tenant_id'=>$this->shop_tenant_id
            ])
            ->find();

        if(!$is_exist){
            return  $this->addGoods($goods_spu);
        }else{
            return $this->updateGoodsInfo($goods_spu);
        }
    }

    //添加商品
    protected function addGoods($goods_spu){
        $server = $this->server;
        $tenant_id = $this->shop_tenant_id;
        Db::startTrans();
        try {
            $result = (new \catchAdmin\externalGoods\model\Goods())
                ->where('goods_spu',$goods_spu)->find();


            if(!$result){
                throw new Exception('商品不存在');
            }
            $result = $result->toArray();
            $value = [];
            $value['tenant_id'] = $this->shop_tenant_id;
            $value['prod'] = $result['goods_spu'];
            $value['formerprice'] = round($result['cost_price'] * $this->percet);
            $value['final_cost'] = round($result['cost_price'] * $this->percet);
            $value['goods_name'] = $result['goods_name'];
            $value['photo'] = array_merge([$result['goods_img']], json_decode($result['goods_slideshow_img'],true));
            $value['photo'] = implode(',',$value['photo']);
            $value['stock'] = $result['stock'];
            $value['description'] ='';
            $value['detail_img'] = $result['description'];
            $value['barcode'] = $result['barcode'];
            $value['product_area'] = $result['origin_name'];

            $category_arr = (new Category)->field('level,name')->where('id',$result['category_id'])->find();

            if($category_arr){
                $category_arr = $category_arr->toArray();
                $sss_sno =  Db::connect($this->server)->table('posap')->where(
                    [
                        'tradeid'=> $this->shop_tenant_id,
                        'LAYER'=> $category_arr['level'] ,
                        'SNAME'=>$category_arr['name'],
                    ]
                )->value('SNO');
                $value['type'] = $sss_sno;
            }else{
                $value['type'] = NULL;
            }

            //跨境
            if(in_array($result['trade_type_id'] ,[1,4,5])){
                $value['is_cross_border'] = 1;
            }

            //上下架
            if($result['is_sale'] == 1){
                $value['is_show'] = 0;
            }else{
                $value['is_show'] = 1;
            }

            $value['orders'] = 28;//默认权限
            $value['source'] = 1;
            $value['shows'] = 0;//首页不显示



            $insertGetId =  Db::connect($this->server)->table('db_product')->insertGetId($value);
            $goods_spu = $value['prod'];
            $goods_pk_id = $result['id'];


            //-----------商品属性记录
            $goods_attr = (new GoodsAttribute)->field('name,attribute_name')->where('goods_id',$goods_pk_id)->select()->toArray();
            $attr_arr = [];
            foreach ($goods_attr as $attr_v){
                if(!in_array($attr_v['attribute_name'],$attr_arr)) {
                    $attr_arr[$attr_v['name']][] = $attr_v['attribute_name'];
                }
            }
            //处理属性
            foreach ($attr_arr as $k => $v){
                $remote_attr = Db::connect($server)->table('db_property')
                    ->field('sid,cbval')
                    ->where([
                        'SNO'=> $value['type'],//分类 = 跨进电商
                        'tradeid'=> $tenant_id,
                        'property'=>$k
                    ])->find();


                if($remote_attr){//存在属性名
                    $cbvalArr = explode('$',$remote_attr['cbval']);

                    foreach ($v as $kk){
                        if(!in_array($kk , $cbvalArr)){//属性值不存在的话，
                            $cbvalArr[] = $kk;
                        }
                    }
                    $cbval = implode('$',$cbvalArr);
                    //更新
                    Db::connect($server)->table('db_property')->where('sid',$remote_attr['sid'])->update([
                        'cbval'=>$cbval
                    ]);

                }else{
                    $cbval = implode('$',$v);
                    //新增
                    $res =  Db::connect($server)->table('db_property')->insert([
                        'SNO'=>$value['type'],
                        'property'=>$k,
                        'tradeid'=>$tenant_id,
                        'cbval'=>$cbval,
                        'english'=>'',
                        'value'=>'',
                        'if'=>'否'
                    ]);

                    if(!$res){
                        Log::error('property' . json_encode([
                                'SNO'=>$value['type'],
                                'property'=>$k,
                                'tradeid'=>$tenant_id,
                                'cbval'=>$cbval,
                                'english'=>'',
                                'value'=>'',
                                'if'=>'否'
                            ]));
                    }
                }
            }


            //-----------商品规格
            //查询规格记录
            $goods_rule = (new GoodsRule)->field('sku_name,sku_price,sku_stock,cost_price,goods_sku')->where('goods_id',$goods_pk_id)->select()->toArray();

            $rulesArr = [];
            foreach ($goods_rule as $gr_v){
                $rule_name_arr =[];
                $rule_value_arr = [];
                $sku_list = explode(';',$gr_v['sku_name']);

                //dd($sku_list);

                foreach ($sku_list as $sku){
                    $rule_name_arr[] = explode(':',$sku)[0];
                    $rule_value_arr[] = explode(':',$sku)[1];
                }

                //查询 pr_id
                $sid_arr =  Db::connect($server)->table('db_property')
                    ->where([
                        ['property','in',$rule_name_arr],
                        ['SNO','=',$value['type']],
                        ['tradeid','=',$tenant_id]
                    ])
                    ->column('sid');

                $rulesArr[] =   [
                    'pid'=>$goods_spu,
                    'pr_id'=>implode(',',$sid_arr),
                    'pr_name'=>implode(',',$rule_name_arr),
                    'suk_val'=>implode(',',$rule_value_arr),
                    'suk_num'=>$gr_v['sku_stock'],
                    'suk_price'=> round($gr_v['cost_price'] * $this->percet),
                    'cost_price'=> round($gr_v['cost_price'] * $this->percet),
                    'if_stock'=>1,
                    'tradeid'=>$tenant_id,
                    'sku_id'=>$gr_v['goods_sku']
                ];
            }
            Db::connect($server)->table('db_pro_attr')->limit(100)->insertAll($rulesArr);

            return true;
        }catch (\Exception $e){
            Db::rollback();
            return false;
        }
    }

    //修改商品
    protected function updateGoodsInfo($goods_spu){
        $server = $this->server;
        $tenant_id = $this->shop_tenant_id;
        Db::startTrans();
        try {
            $result = (new \catchAdmin\externalGoods\model\Goods())
                ->where('goods_spu',$goods_spu)->find();

            if(!$result){
                throw new Exception('系统商品不存在');
            }

            $is_exist =  Db::connect($this->server)->table('db_product')
                ->where([
                    'ifshow'=>1,
                    'prod'=>$goods_spu,
                    'tenant_id'=>$this->shop_tenant_id
                ])
                ->find();

            if(!$is_exist){
                throw new Exception('商城商品不存在');
            }

            //dd(33);

            $result = $result->toArray();
            $value = [];
            $value['tenant_id'] = $this->shop_tenant_id;
            $value['prod'] = $result['goods_spu'];
            $value['formerprice'] = round($result['cost_price'] * $this->percet);
            $value['final_cost'] = round($result['cost_price'] * $this->percet);
            $value['goods_name'] = $result['goods_name'];
            $value['photo'] = array_merge([$result['goods_img']], json_decode($result['goods_slideshow_img'],true));
            $value['photo'] = implode(',',$value['photo']);
            $value['stock'] = $result['stock'];
            $value['description'] ='';
            $value['detail_img'] = $result['description'];
            $value['barcode'] = $result['barcode'];
            $value['product_area'] = $result['origin_name'];


            $category_arr = (new Category)->field('level,name')->where('id',$result['category_id'])->find();

            if($category_arr){
                $category_arr = $category_arr->toArray();
                $sss_sno =  Db::connect($this->server)->table('posap')->where(
                    [
                        'tradeid'=> $this->shop_tenant_id,
                        'LAYER'=> $category_arr['level'] ,
                        'SNAME'=>$category_arr['name'],
                    ]
                )->value('SNO');
                $value['type'] = $sss_sno;
            }else{
                throw new Exception('分类错误');
                $value['type'] = NULL;
            }

            //跨境
            if(in_array($result['trade_type_id'] ,[1,4,5])){
                $value['is_cross_border'] = 1;
            }

            //上下架
            if($result['is_sale'] == 1){
                $value['is_show'] = 0;
            }else{
                $value['is_show'] = 1;
            }

            $value['orders'] = 28;//默认权限
            $value['source'] = 1;


            Db::connect($this->server)->table('db_product')->where(['pid'=>$is_exist['pid']])->update($value);
            $goods_spu = $value['prod'];
            $goods_pk_id = $result['id'];


            //-----------商品属性记录
            $goods_attr = (new GoodsAttribute)->field('name,attribute_name')->where('goods_id',$goods_pk_id)->select()->toArray();
            $attr_arr = [];
            foreach ($goods_attr as $attr_v){
                if(!in_array($attr_v['attribute_name'],$attr_arr)) {
                    $attr_arr[$attr_v['name']][] = $attr_v['attribute_name'];
                }
            }
            //处理属性
            foreach ($attr_arr as $k => $v){
                $remote_attr = Db::connect($server)->table('db_property')
                    ->field('sid,cbval')
                    ->where([
                        'SNO'=> $value['type'],//分类 = 跨进电商
                        'tradeid'=> $tenant_id,
                        'property'=>$k
                    ])->find();


                if($remote_attr){//存在属性名
                    $cbvalArr = explode('$',$remote_attr['cbval']);

                    foreach ($v as $kk){
                        if(!in_array($kk , $cbvalArr)){//属性值不存在的话，
                            $cbvalArr[] = $kk;
                        }
                    }
                    $cbval = implode('$',$cbvalArr);
                    //更新
                    Db::connect($server)->table('db_property')->where('sid',$remote_attr['sid'])->update([
                        'cbval'=>$cbval
                    ]);

                }else{
                    $cbval = implode('$',$v);
                    //新增
                    $res =  Db::connect($server)->table('db_property')->insert([
                        'SNO'=>$value['type'],
                        'property'=>$k,
                        'tradeid'=>$tenant_id,
                        'cbval'=>$cbval,
                        'english'=>'',
                        'value'=>'',
                        'if'=>'否'
                    ]);

                    if(!$res){
                        Log::error('property' . json_encode([
                                'SNO'=>$value['type'],
                                'property'=>$k,
                                'tradeid'=>$tenant_id,
                                'cbval'=>$cbval,
                                'english'=>'',
                                'value'=>'',
                                'if'=>'否'
                            ]));
                    }
                }
            }


            //-----------商品规格
            $this->dealRule($goods_pk_id,$goods_spu,$value['type'],$tenant_id);

            return true;
        }catch (\Exception $e){
            Db::rollback();
            return false;
        }
    }

    private function dealRule($goods_pk_id,$goods_spu,$goods_type,$tenant_id){
        $server = $this->server;
        //$tenant_id = $this->shop_tenant_id;
        //-----------商品规格
        //新
        $new_goods_rule = (new GoodsRule)->field('sku_name,sku_price,sku_stock,cost_price,goods_sku')->where('goods_id',$goods_pk_id)->select()->toArray();
        $new_sku_ids = array_column($new_goods_rule,'goods_sku');
        //老
        $old_goods_rule =  Db::connect($server)->table('db_pro_attr')->where(['tradeid'=>$tenant_id, 'pid'=>$goods_spu])->select()->toArray();
        $old_sku_ids = array_column($old_goods_rule,'sku_id');
        $old_goods_rule_combine = array_combine($old_sku_ids,$old_goods_rule);

        // 查找新增的元素
        $newElements = array_diff($new_sku_ids, $old_sku_ids);

        // 查找需要修改的元素
        $modifyElements = array_intersect($new_sku_ids, $old_sku_ids);

        // 查找需要删除的元素
        $deleteElements = array_diff($old_sku_ids, $new_sku_ids);


        foreach ($new_goods_rule as $value){
            //组装数据
            $rule_name_arr =[];
            $rule_value_arr = [];
            $sku_list = explode(';',$value['sku_name']);

            //dd($sku_list);

            foreach ($sku_list as $sku){
                $rule_name_arr[] = explode(':',$sku)[0];
                $rule_value_arr[] = explode(':',$sku)[1];
            }

            //查询 pr_id
            $sid_arr =  Db::connect($server)->table('db_property')
                ->where([
                    ['property','in',$rule_name_arr],
                    ['SNO','=',$goods_type],
                    ['tradeid','=',$tenant_id]
                ])
                ->column('sid');

            $rulesArr =   [
                'pid'=>$goods_spu,
                'pr_id'=>implode(',',$sid_arr),
                'pr_name'=>implode(',',$rule_name_arr),
                'suk_val'=>implode(',',$rule_value_arr),
                'suk_num'=>$value['sku_stock'],
                'suk_price'=> round($value['cost_price'] * $this->percet),
                'cost_price'=> round($value['cost_price'] * $this->percet),
                'if_stock'=>1,
                'tradeid'=>$tenant_id,
                'sku_id'=>$value['goods_sku']
            ];

            if(in_array($value['goods_sku'],$newElements)){//新增的
                Db::connect($server)->table('db_pro_attr')->insert($rulesArr);
            }elseif (in_array($value['goods_sku'],$modifyElements)){//修改的
                //unset($rulesArr['suk_price']);//修改的时候不更新价格
                Db::connect($server)->table('db_pro_attr')->where(['id'=>$old_goods_rule_combine[$value['goods_sku']]['id']])->update($rulesArr);
            }
        }

        //删除规格
        if(!empty($deleteElements)){
            Db::connect($server)->table('db_pro_attr')->where([
                ['tradeid','=',$tenant_id],
                ['pid','=',$goods_spu],
                ['sku_id','in',$deleteElements],
            ])->delete();
        }

    }

    //物流通知
    public function notifyTrack($param){
        //查询物流轨迹
        $order_no = $param['order_no'];
        $logisticsApi = new OrderApi;
        $apiData = $logisticsApi->logistics(['order_no'=>$order_no])['data'];

//        $apiData = [
//            [
//                "express_no"=> "qwe123123", //快递编号
//            "express_code"=> "EMS", //快递Code
//            "express_remark"=> "", //快递备注
//            "content"=>"[{\"Action\":\"1\",\"AcceptStation\":\"【潮州市】广东潮州市公司-林洪耿（0768-3275198|0768-2337000） 已揽收\",\"AcceptTime\":\"2022-04-22 20:06:48\",\"Remark\":\"\",\"Location\":\"潮州市\"},{\"Action\":\"2\",\"AcceptStation\":\"【潮州市】已离开 广东潮州市公司；发往 湖北武汉地区包\",\"AcceptTime\":\"2022-04-22 20:12:48\",\"Remark\":\"\",\"Location\":\"潮州市\"},{\"Action\":\"2\",\"AcceptStation\":\"【揭阳市】已到达 广东揭阳分拨交付中心\",\"AcceptTime\":\"2022-04-22 21:34:02\",\"Remark\":\"\",\"Location\":\"揭阳市\"},{\"Action\":\"2\",\"AcceptStation\":\"【揭阳市】已离开 广东揭阳分拨交付中心；发往 湖北武汉分拨交付中心\",\"AcceptTime\":\"2022-04-22 21:36:22\",\"Remark\":\"\",\"Location\":\"揭阳市\"},{\"Action\":\"2\",\"AcceptStation\":\"已到达 湖北武汉分拨交付中心\",\"AcceptTime\":\"2022-04-23 20:22:37\",\"Remark\":\"\",\"Location\":\"武汉市\"},{\"Action\":\"2\",\"AcceptStation\":\"已离开 湖北武汉分拨交付中心；发往 湖北武汉三角湖公司\",\"AcceptTime\":\"2022-04-23 20:49:26\",\"Remark\":\"\",\"Location\":\"武汉市\"},{\"Action\":\"2\",\"AcceptStation\":\"已到达 湖北武汉三角湖公司[027-59621483]\",\"AcceptTime\":\"2022-04-24 08:27:58\",\"Remark\":\"\",\"Location\":\"武汉市\"}]", //物流信息
//            "express_name"=> "EMS" //快递名称
//            ]
//        ];



        if(empty($apiData)){
            return false;
        }

        $insert = [];

        $HnOrderDetailModel = new HnOrderDetail;
        $orderChildId = $HnOrderDetailModel->where(['order_no'=>$order_no])->value('source_order_no');

        //////////$orderChildId = 'A111117133170471006_1';

        $orderId = Db::connect($this->server)->table('db_app_orderlist')->where(['chilOrdId'=>$orderChildId])->value('orderId');


        //查询物流是否存在
        $is_exist =  Db::connect($this->server)->table('db_jike_order')
            ->where([
                'orderId'=>$orderId,
                'chilOrdId'=>$orderChildId,
                'deleted_at'=>0
            ])
            ->find();

        if($is_exist) return true;

        //处理物流
        $insert= [];
        foreach ($apiData as $value){
            if(!empty($insert)) array_push($insert['extraPostid'],$value['express_no']);
            else $insert = [
                'orderId'=>$orderId,
                'chilOrdId'=>$orderChildId,
                'mainPostid'=>$value['express_no'],
                'tenant_id'=>$this->shop_tenant_id,
                'tradeNo'=>$order_no,
                'source'=>1,
                'express_name'=>$value['express_name'],
                'express_code'=>$value['express_code'],
                'extraPostid'=>[]
            ];
        }
        //处理商品 。。。

        Db::startTrans();
        try {
            if(!empty($insert)) $insert['extraPostid'] = implode(',',$insert['extraPostid']);
            Db::connect($this->server)->table('db_jike_order')->insert($insert);

            Db::connect($this->server)->table('db_app_order')->where('orderId',$orderId)->update([
                'orderStatus'=>3//修改为 待收货=已发货
            ]);
            Db::commit();
            return true;
        } catch (\Exception $exception) {
            Db::rollback();
//            throw new Exception($exception->getMessage());
            return false;
        }
    }

    //发货通知
    public function notifySend($param){
        $order_id = $param['source_order_no'];//来源订单号
        $order_no = $param['order_no'];//候鸟内部订单号
        $express = $param['express'];//快递数组

        $_orderId = Db::connect($this->server)->table('db_app_orderlist')->where(['chilOrdId'=>$order_id])->value('orderId');

        //查询物流是否存在
        $is_exist =  Db::connect($this->server)->table('db_jike_order')
            ->where([
                'orderId'=>$_orderId,
                'chilOrdId'=>$order_id,
                'deleted_at'=>0
            ])
            ->find();

        if($is_exist) return true;

        //处理物流
        $insert= [];
        foreach ($express as $value){
            if(!empty($insert)) array_push($insert['extraPostid'],$value['express_no']);
            else $insert = [
                'orderId'=>$_orderId,
                'chilOrdId'=>$order_id,
                'mainPostid'=>$value['express_no'],
                'tenant_id'=>$this->shop_tenant_id,
                'tradeNo'=>$order_no,
                'source'=>1,
                'express_name'=>$value['express_name'],
                'express_code'=>$value['express_code'],
                'extraPostid'=>[]
            ];
        }
        //处理商品 。。。

        Db::startTrans();
        try {
            if(!empty($insert)) $insert['extraPostid'] = implode(',',$insert['extraPostid']);
            Db::connect($this->server)->table('db_jike_order')->insert($insert);

            Db::connect($this->server)->table('db_app_order')->where('orderId',$_orderId)->update([
                'orderStatus'=>3//修改为 待收货=已发货
            ]);


            Db::commit();
            return true;
        } catch (\Exception $exception) {
            Db::rollback();
//            throw new Exception($exception->getMessage());
            return false;
        }
    }

    public function notifyOrderStatusSend($param){
//        {
//            "customs_time":1670653008,
//            "order_no":"2022113009167",
//            "order_status":2,
//            "source_order_no":"20221130191154680153"
//        }
        $orderStatusOptions = [
            -3=>'异常订单',
            -2=>'是待付款',
            -1=>'已取消',
            0=>'待发货',
            1=>'已发货、待收货',
            2=>'已收货',
            3=>'海关审核中|仓库分拣打包中',
            5=>'已完成',
        ];

        $notify_order_status = $param['order_status'];
        $update_order_status = null;
        $update_orderlist_status = null;
        if(1 == $notify_order_status){//待收货
            $update_order_status = 3;
        }elseif (2 == $notify_order_status){//已收货
            $update_order_status = 3;
            $update_orderlist_status = 1;//子订单已收货
        }elseif (5 == $notify_order_status){//已完成
            $update_order_status = 3;
            $update_orderlist_status = 1;//子订单已收货
        }

        //判断是否添加了 物流单
        $_orderId = Db::connect($this->server)->table('db_app_orderlist')->where(['chilOrdId'=>$param['source_order_no']])->value('orderId');

        //查询物流是否存在
        $is_exist =  Db::connect($this->server)->table('db_jike_order')
            ->where([
                'orderId'=>$_orderId,
                'chilOrdId'=>$param['source_order_no'],
                'deleted_at'=>0
            ])
            ->find();

        //不存在物流单
        if(!$is_exist) {
            $logisticsApi = new OrderApi;
            $apiData = $logisticsApi->logistics(['order_no'=>$param['order_no']])['data'];

//            待注释
//            $apiData = [
//                [
//                    "express_no"=> "qwe" . time() . mt_rand(10000,99999) , //快递编号
//                "express_code"=> "EMS", //快递Code
//                "express_remark"=> "", //快递备注
//                "content"=>"[{\"Action\":\"1\",\"AcceptStation\":\"【潮州市】广东潮州市公司-林洪耿（0768-3275198|0768-2337000） 已揽收\",\"AcceptTime\":\"2022-04-22 20:06:48\",\"Remark\":\"\",\"Location\":\"潮州市\"},{\"Action\":\"2\",\"AcceptStation\":\"【潮州市】已离开 广东潮州市公司；发往 湖北武汉地区包\",\"AcceptTime\":\"2022-04-22 20:12:48\",\"Remark\":\"\",\"Location\":\"潮州市\"},{\"Action\":\"2\",\"AcceptStation\":\"【揭阳市】已到达 广东揭阳分拨交付中心\",\"AcceptTime\":\"2022-04-22 21:34:02\",\"Remark\":\"\",\"Location\":\"揭阳市\"},{\"Action\":\"2\",\"AcceptStation\":\"【揭阳市】已离开 广东揭阳分拨交付中心；发往 湖北武汉分拨交付中心\",\"AcceptTime\":\"2022-04-22 21:36:22\",\"Remark\":\"\",\"Location\":\"揭阳市\"},{\"Action\":\"2\",\"AcceptStation\":\"已到达 湖北武汉分拨交付中心\",\"AcceptTime\":\"2022-04-23 20:22:37\",\"Remark\":\"\",\"Location\":\"武汉市\"},{\"Action\":\"2\",\"AcceptStation\":\"已离开 湖北武汉分拨交付中心；发往 湖北武汉三角湖公司\",\"AcceptTime\":\"2022-04-23 20:49:26\",\"Remark\":\"\",\"Location\":\"武汉市\"},{\"Action\":\"2\",\"AcceptStation\":\"已到达 湖北武汉三角湖公司[027-59621483]\",\"AcceptTime\":\"2022-04-24 08:27:58\",\"Remark\":\"\",\"Location\":\"武汉市\"}]", //物流信息
//                "express_name"=> "EMS" //快递名称
//                ]
//            ];

            if(!empty($apiData)){
                $insert= [];
                foreach ($apiData as $value){
                    if(!empty($insert)) array_push($insert['extraPostid'],$value['express_no']);
                    else $insert = [
                        'orderId'=>$_orderId,
                        'chilOrdId'=>$param['source_order_no'],
                        'mainPostid'=>$value['express_no'],
                        'tenant_id'=>$this->shop_tenant_id,
                        'tradeNo'=>$param['order_no'],
                        'source'=>1,
                        'express_name'=>$value['express_name'],
                        'express_code'=>$value['express_code'],
                        'extraPostid'=>[]
                    ];
                }

                if(!empty($insert)) $insert['extraPostid'] = implode(',',$insert['extraPostid']);
                Db::connect($this->server)->table('db_jike_order')->insert($insert);
            }
        }

        //修改主订单状态
        if(null !== $update_order_status){
            Db::connect($this->server)->table('db_app_order')->where('orderId',$_orderId)->update([
                'orderStatus'=>$update_order_status
            ]);
        }

        //修改子订单收货状态
        if(null !== $update_orderlist_status){
            Db::connect($this->server)->table('db_app_orderlist')->where('chilOrdId',$param['source_order_no'])->update([
                'trade_status'=>$update_orderlist_status
            ]);
        }

        return true;
    }
}